package common.server.fallback;

import common.server.entity.InsideRequestMessage;
import common.server.entity.InsideResponseMessage;
import common.server.entity.OutsideRequestMessage;
import common.server.entity.OutsideResponseMessage;
import common.server.respcode.RespCodeService;
import common.server.respcode.RespHelper;
import feign.hystrix.FallbackFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;

/**
 * @Title: ServiceFallbackFactory
 * @ProjectName com-bigwavn-group
 * @Description: 服务熔断工厂
 * @author: wangweitao 1749343503@qq.com
 * @date: 2019/6/4 16:21
 * @version: V1.0.0
 */
public abstract class ServiceFallbackFactory<T>
		implements FallbackFactory<T> {

	/**
	 *
	 * @return
	 */
	protected abstract T newConstant();

	/**
	 *
	 * @param throwable
	 * @return
	 */
	@Override
	public T create(Throwable throwable) {
		if (StringUtils.isNotBlank(throwable.getMessage())
				|| !(throwable instanceof RuntimeException)) {
			LoggerFactory.getLogger(ServiceFallbackFactory.class).error(
					"fallback due to: " + throwable.getMessage(), throwable);

		}
		return newConstant();
	}

	/**
	 * 构建内部熔断返回响应
	 * 
	 * @param req
	 * @return
	 */
	protected static InsideResponseMessage<?> buildInsideFallbackResp(
			InsideRequestMessage<?> req) {
		return RespHelper.buildInsideRespMessage(RespCodeService.COMM_FALLBACK,
				null);
	}

	/**
	 * 构建外部熔断返回响应
	 * 
	 * @param req
	 * @return
	 */
	protected static OutsideResponseMessage<?> buildOutsideFallbackResp(
			OutsideRequestMessage<?> req) {
		return RespHelper.buildOutsideRespMessage(RespCodeService.COMM_FALLBACK,
				null);
	}
}
